#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
from pathlib import Path


DOC_PATH = r"/Users/cangjie_nj/Documents/code/doc"
def find_unused_images():
    """
    查找文档目录下所有未被 Markdown 文件引用的图片文件
    """
    # 支持的图片扩展名
    image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.svg', '.webp', '.PNG', '.JPG', '.JPEG', '.GIF', '.BMP', '.SVG', '.WEBP'}
    
    # 获取当前工作目录
    doc_root = Path('/Users/cangjie_nj/Documents/code/doc')
    
    # 查找所有图片文件
    all_images = []
    for file_path in doc_root.rglob("."):
        if file_path.is_file() and file_path.suffix in image_extensions:
            all_images.append(file_path)
    
    print(f"找到 {len(all_images)} 个图片文件")
    
    # 查找所有 Markdown 文件
    md_files = list(doc_root.rglob('*.md'))
    print(f"找到 {len(md_files)} 个 Markdown 文件")
    
    # 收集所有在 Markdown 文件中被引用的图片路径
    referenced_images = set()
    
    # 正则表达式匹配 Markdown 图片语法 ![alt](path) 或 <img src="path">
    img_patterns = [
        re.compile(r'!\[.*?\]\((.+?)\)'),  # 匹配 ![alt](path)
        re.compile(r'<img[^>]+src=["\']([^"\']+)["\']', re.IGNORECASE)  # 匹配 <img src="path">
    ]
    
    for md_file in md_files:
        try:
            with open(md_file, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # 检查图片引用
                for pattern in img_patterns:
                    matches = pattern.findall(content)
                    for match in matches:
                        # 将相对路径转换为绝对路径
                        img_path = Path(md_file).parent / match
                        referenced_images.add(img_path.resolve())
        except Exception as e:
            print(f"读取文件 {md_file} 时出错: {e}")
    
    print(f"发现 {len(referenced_images)} 个被引用的唯一图片")
    
    # 找出未被使用的图片
    unused_images = []
    for img in all_images:
        # 检查图片是否被引用
        if img.resolve() not in referenced_images:
            # 特殊处理：检查是否是 Excalidraw 文件相关的图片
            # Excalidraw 的 .excalidraw.md 文件通常与同名图片关联
            is_excalidraw_related = False
            if img.with_suffix('').with_suffix('.excalidraw.md').exists():
                is_excalidraw_related = True
            
            if not is_excalidraw_related:
                unused_images.append(img)
    
    # 输出结果
    if unused_images:
        print("\n以下图片未被任何 Markdown 文件引用:")
        for img in unused_images:
            print(f"rm -rf {img}")
    else:
        print("\n没有发现未被使用的图片文件")

if __name__ == "__main__":
    find_unused_images()
